import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
NProgress.configure({ showSpinner: false }) // NProgress Configuration
import getPageTitle from '@/utils/get-page-title'
import { asyncRoutes } from '@/router/index'

router.beforeEach((to, from, next) => {
  // 修改标题
  document.title = getPageTitle(to.meta.title)
  next()
})

// 白名单：不需要token就可以直接访问页面
const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  // 启动进度条
  NProgress.start()

  // 获取token
  const token = store.state.user.token
  if (token) {
    // 是否去登陆页
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 是否有个人信息
      const userId = store.state.user.userInfo.userId
      if (!userId) {
        // 获取用户信息--包括可以访问那些页面
        const menus = await store.dispatch('user/getUserProfile')
        console.log('用户能访问的页面', menus, asyncRoutes)

        // filterRouters：当前用户访问的8个页面的那几个
        const filterRouters = asyncRoutes.filter(item => {
          const name = item.children[0].name
          return menus.includes(name)
        })

        // 解决刷新跳转404问题
        // 让404在路由配置的最后面
        filterRouters.push(
          // 404 page must be placed at the end !!!
          { path: '*', redirect: '/404', hidden: true }
        )

        // 动态生成可以访问的动态路由
        router.addRoutes(filterRouters)

        // 把动态路由添加到vuex中
        store.commit('menu/setMenuList', filterRouters)

        // 解决刷新出现的白屏bug
        next({
          ...to,
          replace: true
        })
      } else {
        next()
      }
    }
  } else {
    // 是否白名单 login
    // if (to.path === '/login' || to.path === '/404') {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      // 没有token，去的不是login
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  // 结束进度条
  NProgress.done()
})

// import { Message } from 'element-ui'

// import { getToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title'

// const whiteList = ['/login'] // no redirect whitelist

// router.beforeEach(async(to, from, next) => {
//   // start progress bar
//   NProgress.start()

//   // set page title
//   document.title = getPageTitle(to.meta.title)

//   // determine whether the user has logged in
//   const hasToken = getToken()

//   if (hasToken) {
//     if (to.path === '/login') {
//       // if is logged in, redirect to the home page
//       next({ path: '/' })
//       NProgress.done()
//     } else {
//       const hasGetUserInfo = store.getters.name
//       if (hasGetUserInfo) {
//         next()
//       } else {
//         try {
//           // get user info
//           await store.dispatch('user/getInfo')

//           next()
//         } catch (error) {
//           // remove token and go to login page to re-login
//           await store.dispatch('user/resetToken')
//           Message.error(error || 'Has Error')
//           next(`/login?redirect=${to.path}`)
//           NProgress.done()
//         }
//       }
//     }
//   } else {
//     /* has no token*/

//     if (whiteList.indexOf(to.path) !== -1) {
//       // in the free login whitelist, go directly
//       next()
//     } else {
//       // other pages that do not have permission to access are redirected to the login page.
//       next(`/login?redirect=${to.path}`)
//       NProgress.done()
//     }
//   }
// })

// router.afterEach(() => {
//   // finish progress bar
//   NProgress.done()
// })
